package group.sicher.core.web.handler;

import group.sicher.core.web.response.SicherResponse;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

/**
 * description:
 * mvc 返回值统一处理 统一处理成SicherResponse实体结构 标准输出到前端
 * author:dengjinde
 * date:2019/3/18
 */
public class SicherResponseValueHandler implements HandlerMethodReturnValueHandler {

    private RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor;

    /**
     * 构造函数
     *
     * @param requestResponseBodyMethodProcessor
     */
    public SicherResponseValueHandler(RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor) {
        this.requestResponseBodyMethodProcessor = requestResponseBodyMethodProcessor;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseBody.class) || returnType.hasMethodAnnotation(ResponseBody.class));
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        SicherResponse response = null;
        if (!SicherResponse.class.isAssignableFrom(returnType.getParameterType())) {

            response = new SicherResponse(SicherResponse.SUCCESS_CODE, "success", returnValue);

        } else {
            response = (SicherResponse) returnValue;
        }
        this.requestResponseBodyMethodProcessor.handleReturnValue(response, returnType, mavContainer, webRequest);
    }
}
